package com.aorise.controller.organ;

import com.aorise.exception.ServiceException;
import com.aorise.service.organ.OrganService;
import com.aorise.model.organ.*;
import com.aorise.utils.*;
import com.aorise.utils.json.JsonResponseData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:cat
 * @Desicription: 组织架构控制器类
 * @Date:Created in 2019-05-23
 * @Modified By:
 */
@RestController
@Api(description ="组织架构信息接口")
public class OrganController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OrganService organService;

    /**
     * 查询所有组织架构信息
     * HTTP 方式：GET
     * API 路径：/api/organ
     * 方法名：getAllOrganList
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-05-23
     */
    @ApiOperation(value = "查询所有组织架构信息", httpMethod = "GET", response = String.class, notes = "查询所有组织架构信息,提供组织机构管理-查询组织架构列表使用")
    @RequestMapping(value = "/api/organ", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getAllOrganList() {
        logger.debug("Request RESTful API:getAllOrganList");

        try {
            List<OrganModel> organModelList = organService.getAllOrganList();
            return new JsonResponseData(true,
                    StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", organModelList).toString();
        } catch (DataAccessException e) {
            logger.error(
                    "controller:OrganController. function:getAllOrganList...msg:Get All Organ List DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:OrganController. function:getAllOrganList...msg:Get All Organ List Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 查询所有组织架构信息（树形）
     * HTTP 方式：GET
     * API 路径：/api/organ
     * 方法名：getAllOrganListTree
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-05-23
     */
    @ApiOperation(value = "查询所有组织架构信息（树形）", httpMethod = "GET", response = String.class, notes = "查询所有组织架构信息（树形）,提供所有页面查询组织架构下拉列表使用")
    @RequestMapping(value = "/api/organ/tree", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getAllOrganListTree() {
        logger.debug("Request RESTful API:getAllOrganListTree");

        try {
            List<OrganModel> organModelList = organService.getAllOrganListTree();
            return new JsonResponseData(true,
                    StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", organModelList).toString();
        } catch (DataAccessException e) {
            logger.error(
                    "controller:OrganController. function:getAllOrganListTree...msg:Get All Organ List Tree DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:OrganController. function:getAllOrganListTree...msg:Get All Organ List Tree Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 根据ID查询组织架构详情
     * HTTP 方式：GET
     * API 路径：/api/organ/id/{id}
     * 方法名：getOrganById
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-05-23
     */
    @ApiOperation(value = "根据ID查询组织架构详情", httpMethod = "GET", response = String.class, notes = "根据ID查询组织架构详情，提供组织机构管理-查询组织架构详情使用")
    @RequestMapping(value = "/api/organ/id/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getOrganById(@ApiParam(value = "ID", required = true) @PathVariable(value = "id", required = true) Integer id) {

        logger.debug("Request RESTful API:getOrganById");
        logger.debug("id" + id);

        try {
            OrganModel organModel = organService.getOrganById(id);
            return new JsonResponseData(true,
                    StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", organModel).toString();
        } catch (DataAccessException e) {
            logger.error(
                    "controller:OrganController. function:getOrganById...msg:Get Organ By Id DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:OrganController. function:getOrganById...msg:Get Organ By Id Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 新增组织架构信息
     * HTTP 方式：POST
     * API 路径：/api/organ
     * 方法名：addOrgan
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-05-23
     */
    @ApiOperation(value = "新增组织架构信息", httpMethod = "POST", response = String.class, notes = "新增组织架构信息，提供组织机构管理-新增组织架构使用")
    @RequestMapping(value = "/api/organ", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody
    String addOrgan(@RequestBody @Validated OrganAddVO organAddVO, BindingResult result) {

        logger.debug("Request RESTful API:addOrgan");
        logger.debug("organAddVO：" + organAddVO);

        try {
            if (result.hasErrors()) {
                return JsonResponseData.ofMessage(StatusDefine.DATA_FORMAT_ERROR, result.getFieldError().getDefaultMessage());
            }
            int ret = organService.addOrgan(organAddVO);

            if (ret > 0) {
                return new JsonResponseData(true,
                        StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", ret).toString();
            } else {
                return new JsonResponseData(false,
                        "", StatusDefine.FAILURE, StatusDefineMessage.GetMessage(StatusDefine.FAILURE), "").toString();
            }
        } catch (DataAccessException e) {
            logger.error(
                    "controller:OrganController. function:addOrgan...msg:Add Organ DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:OrganController. function:addOrgan...msg:Add Organ Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 修改组织架构信息
     * HTTP 方式：PUT
     * API 路径：/api/organ
     * 方法名：updateOrgan
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-05-23
     */
    @ApiOperation(value = "修改组织架构信息", httpMethod = "PUT", response = String.class, notes = "修改组织架构信息，提供组织机构管理-编辑组织架构使用")
    @RequestMapping(value = "/api/organ", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody
    String updateOrgan(@RequestBody @Validated OrganEditVO organEditVO, BindingResult result) {
        logger.debug("Request RESTful API:updateOrgan");
        logger.debug("organEditVO：" + organEditVO);

        try {
            if (result.hasErrors()) {
                return JsonResponseData.ofMessage(StatusDefine.DATA_FORMAT_ERROR, result.getFieldError().getDefaultMessage());
            }
            int ret = organService.updateOrgan(organEditVO);

            if (ret > 0) {
                return new JsonResponseData(true,
                        StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", "").toString();
            } else {
                return new JsonResponseData(false,
                        "", StatusDefine.FAILURE, StatusDefineMessage.GetMessage(StatusDefine.FAILURE), "").toString();
            }
        } catch (DataAccessException e) {
            logger.error(
                    "controller:OrganController. function:updateOrgan...msg:Update Organ DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:OrganController. function:updateOrgan...msg:Update Organ Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 删除组织架构信息
     * HTTP 方式：DELETE
     * API 路径：/api/organ/id/{id}
     * 方法名：deleteOrgan
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-05-23
     */
    @ApiOperation(value = "删除组织架构信息", httpMethod = "DELETE", response = String.class, notes = "删除组织架构信息，提供综合监管平台-综合信息发布-删除组织架构使用")
    @RequestMapping(value = "/api/organ/id/{id}", method = RequestMethod.DELETE, produces = "application/json")
    public String deleteOrgan(@ApiParam(value = "ID", required = true) @PathVariable(value = "id", required = true) Integer id,
                              @ApiParam(value = "修改人ID", required = true) @RequestParam(value = "editUser", required = true) Integer editUser) {

        logger.debug("Request RESTful API:deleteOrgan");
        logger.debug("id" + id);
        logger.debug("editUser" + editUser);

        try {
            Map<String, Object> map = new HashMap<>();
            map.put("editUser", editUser);
            map.put("state", ConstDefine.STATE_DISABLE);
            map.put("id", id);
            int ret = organService.deleteOrgan(map);

            if (ret > 0) {
                return new JsonResponseData(true,
                        StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", "").toString();
            } else {
                return new JsonResponseData(false,
                        "", StatusDefine.FAILURE, StatusDefineMessage.GetMessage(StatusDefine.FAILURE), "").toString();
            }
        } catch (DataAccessException e) {
            logger.error(
                    "controller:OrganController. function:deleteOrgan...msg:Delete Organ DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (ServiceException e) {
            logger.error(
                    "controller:OrganController. function:deleteOrgan...msg:Delete Organ ServiceException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false,"",
                    StatusDefine.ORGAN_EXIST, e.getMessage(), "").toString();
        } catch (Exception e) {
            logger.error(
                    "controller:OrganController. function:deleteOrgan...msg:Delete Organ Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }
}
